package com.android.fragmentdemo.defineviews
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class NestedScrollRecyclerView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : RecyclerView(context, attributeSet) {

    private var inDownOrUp = false
    private var firstTime = true
    private var mAdapter: Adapter<*>? = null

    init {
        addOnScrollListener(object : OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (recyclerView.layoutManager is LinearLayoutManager) {
                    val mLayoutManager = recyclerView.layoutManager as? LinearLayoutManager
                    val itemPosition =
                        mLayoutManager?.findFirstCompletelyVisibleItemPosition() ?: -1
                    Log.d(TAG, "dy0:${dy},itemPosition == 0:${itemPosition == 0}")
                    //if (!firstTime) {
                        inDownOrUp = itemPosition == 0 && dy >= 0
                    //}
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
            }
        })
    }

    override fun dispatchNestedPreScroll(
        dx: Int,
        dy: Int,
        consumed: IntArray?,
        offsetInWindow: IntArray?,
        type: Int
    ): Boolean {
        //return false
        return super.dispatchNestedPreScroll(dx, dy + 10, consumed, offsetInWindow, type)
    }

    override fun offsetChildrenVertical(dy: Int) {
        super.offsetChildrenVertical(dy)
//        if (firstTime) {
//            inDownOrUp = dy == 0
//            firstTime = false
//        }
        Log.d(TAG, "dy1:${dy}")
    }

    fun initAdapter(mAdapter: Adapter<*>) {
        this.mAdapter = mAdapter
    }

    fun positionInDownOrUp() = inDownOrUp

    fun resetPosition(inDownOrUp: Boolean) {
        this.inDownOrUp = inDownOrUp
    }

    companion object {
        const val TAG = "NestedScrollRecyclerView"
    }
}